package com.dongdongshop.shril;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.pojo.seller.TbSeller;
import com.dongdongshop.service.seller.SellerService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @Author Eayon
 * @Date 2020/2/27 17:27
 */
public class UserRealm extends AuthorizingRealm {

    @Reference
    private SellerService sellerService;

    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从token中获取用户输入的账号密码
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        //调用数据库查看该账号是否存在
        TbSeller seller = sellerService.getSellerById(token.getUsername());
        if(seller == null){
            return null;
        }
        //判断密码
        //第一个参数为：加入密码正确也就是登录成功之后的用户对象 相当于登录成功后用户放入session
        //第二个参数为：数据库查询出来的密码，shiro会自动帮我们和用户输入的密码进行校验
        //第三个：为该用户的盐 该项目中每个商家的盐就是他的id值  ByteSource.Util.bytes(seller.getSellerId())
        //第四个参数为：如果密码正确，这个就是该用户的用户名
        return new SimpleAuthenticationInfo(seller,seller.getPassword(), ByteSource.Util.bytes(seller.getSellerId()),seller.getNickName());
    }
}
